<template>
  <div>
    <h3>发表评论</h3>
    <textarea name id cols="20" rows="5" placeholder="发表评论:不得超过150字" maxlength="150" v-model="msg"></textarea>
    <button type="button" class="mui-btn mui-btn-primary mui-btn-block" @click="speak()">发表评论</button>
    <!--  -->
    <!--  -->
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,i) in comments" :key="item.id">
        <div
          class="cmt-title"
        >第{{i+1}}楼---用户:{{item.user_name}}---发表时间:{{item.add_time | dataFormat}}</div>
        <div class="cmt-body">{{item.content}}</div>
      </div>
    </div>
    <!--  -->
    <!--  -->
    <button
      type="button"
      class="mui-btn mui-btn-danger mui-btn-block mui-btn-outlined"
      @click="add"
    >加载更多</button>
  </div>
</template>
<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      comments: [],
      pageindex: 1, //页数
      msg: "" //评论内容
    };
  },
  created() {
    this.getcomments();
  },
  methods: {
    getcomments() {
      this.$http
        .get(
          "http://www.liulongbin.top:3005/api/getcomments/" +
            this.id +
            "?pageindex=" +
            this.pageindex
        )
        .then(result => {
          var result = result.body;
          if (result.status == 0) {
            this.comments = this.comments.concat(result.message); //concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组，而仅仅会返回被连接数组的一个副本                   //防止数据覆盖
          } else {
            Toast("加载失败");
          }
          // console.log(result);
        });
    },
    //加载更多
    add() {
      this.pageindex++;
      this.getcomments(); //再次调用 刷新评论
    },
    speak() {
      if (this.msg.trim().length == "") {
        Toast("评论不能为空");
      } else {
        this.$http
          .post("http://www.liulongbin.top:3005/api/postcomment/" + this.id, {
            content: this.msg.trim() //首尾没有空格
          })
          .then(result => {
            console.log(result);
            console.log(this.id);

            var result = result.body;
            if (result.status == 0) {
              var cmt = {
                user_name: "匿名用户",
                add_time: Date.now(),
                content: this.msg.trim()
              };
              this.comments.unshift(cmt); //unshift() 方法可向数组的开头添加一个或更多元素，并返回新的长度。  多个一个添加到尾部用push()
              this.msg = "";
              Toast(result.message);
            }
          });
      }
    }
  },
  props: ["id"]
};
</script>
<style scoped>
h3 {
  color: brown;
  margin: 5px;
}
textarea {
  font-size: 14px;
}
.mui-btn-block {
  font-size: 14px;
  padding: 10px;
}
.cmt-title {
  background: #cccccc;
  font-size: 14px;
  color: red;
}
.cmt-body {
  border: 1px solid #cccccc;
  height: 30px;
  font-size: 14px;
  line-height: 30px;
}
</style>
